package com.frxuexi.mymvi

import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import coil3.compose.AsyncImage
import kotlinx.coroutines.launch

@Composable
fun MyAppsPage(vm:AppsViewModel= hiltViewModel()) {
    var list = remember {
        SnapshotStateList<AppsData>()
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect{
                when(it){
                    is AppsState.onSuccess->{
                        Log.i("===",it.data.toString())
                        list.addAll(it.data)
                    }
                    is AppsState.onError->{
                        Log.i("===",it.msg)
                    }

                    else -> {}
                }
            }
        }


        launch {
            //发送意图
            vm.channel.send(AppsIntent.getApps)
        }
    })


    LazyVerticalGrid(verticalArrangement = Arrangement.spacedBy(10.dp), columns = GridCells.Fixed(3), content = {
        items(list){
            AppsItem(entity = it)
        }
    })
}

@Composable
fun AppsItem(entity: AppsData){
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        AsyncImage(model = entity.appIcon, contentDescription = "",
            modifier = Modifier.size(50.dp))
        Text(text = entity.appName)
    }
}